package com.escope.casemanager.controller;

import com.escope.casemanager.model.HttpResult;
import com.escope.casemanager.service.SysUserService;
import com.escope.casemanager.uti.UploadFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 上传接口
 * 2024/3/15
 */
@RestController
@RequestMapping("file")
@CrossOrigin
@Api(value = "上传接口", tags = {"上传接口"})
public class FileController {
    public static final String MODELNAME = "example";
    @Value("${escope.upload.file-path}")
    private String filePath;

    @PostMapping(value = "/upload")
    @ApiOperation("上传文件")
    public HttpResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        return HttpResult.ok(UploadFileUtils.writFile(file, filePath, MODELNAME));
    }

    @GetMapping(value = "/access/{fileName}")
    @ApiOperation("访问上传图片")
    public ResponseEntity<Resource> access(HttpServletRequest request, @PathVariable("fileName") String fileName) throws Exception {
        Resource resource = UploadFileUtils.readFile(fileName, filePath, MODELNAME);
        String contentType = request.getServletContext().getMimeType(fileName);
        return ResponseEntity.ok().contentType(MediaType.valueOf(contentType)).body(resource);
    }

}
